// license-header java merge-point
/**
 * This is only generated once! It will never be overwritten. You can (and have to!) safely modify it by hand.
 */
package org.tinaelle.server.service;

import org.tinaelle.common.dto.AdSequenceDTO;
import org.tinaelle.server.domain.AdSequence;
import org.tinaelle.server.domain.AdSequenceDao;
import org.tinaelle.utils.BootstrapUtils;

/**
 * @see org.tinaelle.service.AdSequenceService
 */
public class AdSequenceServiceImpl extends org.tinaelle.server.service.AdSequenceServiceBase {

	/**
     * 
     */
	private static final long	serialVersionUID	= 1L;

	/**
	 * @see org.tinaelle.service.AdSequenceService#getNextId(java.lang.String)
	 */
	@Override
	protected int handleGetNextId(final java.lang.String tableName) throws java.lang.Exception {
		final AdSequence sequence = getAdSequenceDao().findByTableName( tableName );

		final int nextId = sequence.getCurrentVal() + sequence.getIncrement();
		sequence.setCurrentVal( nextId );
		getAdSequenceDao().update( sequence );

		return nextId;
	}

	/**
	 * @see org.tinaelle.service.AdSequenceService#getNextSystemId(java.lang.String)
	 */
	@Override
	protected int handleGetNextSystemId(final java.lang.String tableName) throws java.lang.Exception {
		final AdSequence sequence = getAdSequenceDao().findByTableName( tableName );

		final int nextId = sequence.getSystemCurrentVal() + sequence.getSystemIncrement();
		sequence.setSystemCurrentVal( nextId );
		getAdSequenceDao().update( sequence );

		return nextId;
	}

	@Override
	protected AdSequenceDTO handleGetByTableName(final String tableName) throws Exception {
		return ( AdSequenceDTO ) getAdSequenceDao().findByTableName( AdSequenceDao.TRANSFORM_ADSEQUENCEDTO, tableName );
	}

	@Override
	protected void handleFillInitialValues() throws Exception {
		/**
		 * Load Sequences
		 */
		{
			// File format :
			// Table Name, CurrentVal, Increment, : 0, 1, 2
			// System Current Val, System Increment : 3, 4
			String[][] sequenceContent = BootstrapUtils.instance().getBootstrapSheetContent( "AdSequence" );
			for ( int i = 1; i < sequenceContent.length; i++ ) {
				final String[] sequenceLine = sequenceContent[ i ];

				if ( sequenceLine.length == 5 ) {
					System.err.println( "Lookup : " + sequenceLine[ 0 ].trim() );
					AdSequenceDTO adSequenceDTO = handleGetByTableName( sequenceLine[ 0 ].trim() );
					if ( adSequenceDTO == null ) {
						adSequenceDTO = new AdSequenceDTO();
						adSequenceDTO.setTableName( sequenceLine[ 0 ].trim() );
						adSequenceDTO.setCurrentVal( Integer.parseInt( sequenceLine[ 1 ].trim() ) );
						adSequenceDTO.setIncrement( Integer.parseInt( sequenceLine[ 2 ].trim() ) );
						adSequenceDTO.setSystemCurrentVal( Integer.parseInt( sequenceLine[ 3 ].trim() ) );
						adSequenceDTO.setSystemIncrement( Integer.parseInt( sequenceLine[ 4 ].trim() ) );
						save( adSequenceDTO );
					}
				}
			}
		}
	}
}